package org.gw.building.ctrl;

import org.apache.commons.lang.StringUtils;
import org.gw.building.model.Tyxxb;
import org.gw.building.model.base.Mz;
import org.gw.building.model.base.Rylx;
import org.gw.building.model.base.Sjly;
import org.gw.building.model.base.Xb;
import org.gw.building.repositories.TyxxbRepository;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.interceptor.RequestPermission;
import org.gw.ylc.base.model.Teacher;
import org.gw.ylc.base.model.UserInfo;
import org.gw.ylc.base.repositories.TeacherRepository;
import org.gw.ylc.base.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by qwx89 on 2017/8/3.
 */
@RestController
@RequestMapping("tgb")
public class TgbCtrl {

    @Autowired
    private TyxxbRepository tyxxbRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    @RequestMapping("list")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public Page<Tyxxb> queryTgb(String gh,String lx){
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        return tyxxbRepository.queryTgb(PermissionUtil.toLikeString(gh),lx,departmentId,RequestContextHolder.get().getPageRequest());
    }

    @RequestMapping("addTgb")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public Tyxxb add(Tyxxb tyxx){
        if(StringUtils.isNotBlank(tyxx.getXh())){
            return tyxxbRepository.save(tyxx);
        }
        Teacher teacher = tyxx.getTeacher();
        if(teacher == null || StringUtils.isBlank(teacher.getEmployeeNo())){
            throw new RuntimeException("请选择教师");
        }
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        tyxx.setYx(departmentId);
        tyxx.setXh(teacher.getEmployeeNo());
        tyxx.setXm(teacher.getName());
        tyxx.setCsrq(teacher.getBirthDate());
        tyxx.setXb(teacher.getSex() == 0 ? new Xb("1") : new Xb("2"));
        tyxx.setWhcd(teacher.getWhcd());
        tyxx.setLx(new Rylx("2"));
        tyxx.setScbz(false);
        tyxx.setSjly(new Sjly("1"));
        tyxx.setMz(new Mz(teacher.getEthnicGroup().getCode()));
        return tyxxbRepository.save(tyxx);

    }

    @RequestMapping("teacher")
    @RequestPermission({RequestPermission.DEPARTMENT})
    public Teacher teacher(String gh){
        return teacherRepository.fingByGh(gh);
    }

    @RequestMapping("deleteTgb")
    @RequestPermission({RequestPermission.DEPARTMENT})
    public void delete(String id){
        tyxxbRepository.delete(id);
    }
}
